package com.ruoyi.back.task

import cn.hutool.core.date.DateUnit
import cn.hutool.core.date.DateUtil
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.ruoyi.back.domain.v2.UserMemberTask
import com.ruoyi.back.service.UserMemberTaskService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Configuration
import org.springframework.scheduling.annotation.EnableScheduling
import org.springframework.scheduling.annotation.Scheduled


@Configuration
@EnableScheduling
class UserMemberScheduleTask {

    @Autowired
    private lateinit var userMemberTaskService: UserMemberTaskService

    //3.添加定时任务
    @Scheduled(cron = "0 0 10,14,16 * * ? ")
    fun configureTasks() {

        userMemberTaskService.list().takeIf { it.isNotEmpty() }
            ?.run {
                forEach { _ ->
                    groupBy { it.memberId }.forEach { (memberId, memberTasks) ->
                        memberTasks.groupBy { it.createBy }.forEach { (createBy, memberTask) ->
                            DateUtil.between(memberTask.maxBy { it.createTime!! }.createTime, DateUtil.date(), DateUnit.HOUR)
                                .takeIf { it > 24 }
                                ?.run {
                                    userMemberTaskService.remove(KtQueryWrapper(UserMemberTask::class.java)
                                        .eq(UserMemberTask::memberId, memberId)
                                        .eq(UserMemberTask::createBy, createBy))
                                }
                        }
                    }
                }
            }
    }

}